//
//  KDKeywordSetController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/3.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDKeywordSetController.h"
#import "KDAddKeywordView.h"
#import "KDProvinceController.h"
#import "KDEditeCellModel.h"
#import "KDNoticeView.h"
#import "KDKeywordNameController.h"
#import "KDKeyWordEditController.h"
#import "KDKeywordGroupEditController.h"
#import "KDMKeywordAddParam.h"
#import "KDMKeywordAddResult.h"
#import "KDMonitorRequestTool.h"
#import "KDBaesMonitorModel.h"
#import "KDReginDataTool.h"
#import "SVProgressHUD.h"
#import "KDReginType.h"
#define AddKeyWordView_Height 44
#define REGIONVIEW_HEIGHT 75
#define CELL_HEIGHT 40
#define NOTICE_LINE_HEIGHT 21
@interface KDKeywordSetController ()<KDAddKeywordViewDelegate, KDKeywordNameControllerDelegate, KDKeyWordEditControllerDelegate, UIAlertViewDelegate, KDKeywordGroupEditControllerDelegate>
/**
 *  控制器底部的scrollView
 */
@property (nonatomic, weak) UIScrollView *underScrollView;
/**
 *  关键词组添加View
 */
@property (nonatomic, weak) KDAddKeywordView *mainwordView;
/**
 *  微博关键词组添加View
 */
@property (nonatomic, weak) KDAddKeywordView *weiboWordView;
/**
 *  不匹配关键词组添加View
 */
@property (nonatomic, weak) KDAddKeywordView *mismatchingWord;

/**
 *  名称View
 */
@property (nonatomic, strong) KDAddKeywordView *addKeywordView;
/**
 *  地区View
 */
@property (nonatomic, weak) KDAddKeywordView *regionView;
/**
 *  单位共享按钮
 */
@property (nonatomic, weak) UIButton *shareBtn;
/**
 *  专题监测按钮
 */
@property (nonatomic, weak) UIButton *specialMonitorBtn;

@property (nonatomic, strong) NSArray *infoArr;
@property (nonatomic, weak) UIButton *saveBtn;
@property (nonatomic, weak) KDNoticeView *noticeView1;
@property (nonatomic, weak) KDNoticeView *noticeView2;
@property (nonatomic, weak) KDNoticeView *noticeView3;
@property (nonatomic, weak) KDNoticeView *noticeView4;
@property (nonatomic, copy) NSString * originalName;

/**
 *  所有de请求参数
 */
@property (nonatomic, strong) KDMKeywordAddParam *param;


@end

@implementation KDKeywordSetController
- (KDMKeywordAddParam *)param{
    if (!_param) {
        _param = [[KDMKeywordAddParam alloc]init];
    }
    return _param;
}
- (NSArray *)infoArr{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
- (void)setUpNavBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
}
#pragma mark - 板块设置区
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
    [self setUpNavBar];
    self.title = @"关键字监测设置";
    [self setUpScrollView];
    [self setUpAddKeyWordView];
//    [self setUpReginView];
    [self setUpMainword];
    [self setUpsecondwordView];
    [self setUpMismatchingWordView];
    [self setUpSaveBtn];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAddress:) name:@"ProvinceAddressToReportControllerNoty" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAddress:) name:@"CityAddressToReportControllerNoty" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAddress:) name:@"TownAddressToReportControllerNoty" object:nil];
    if (self.model) {//如果是编辑进来的，就把数据传好
        self.originalName = self.model.m_Name;
        self.addKeywordView.name = self.model.m_Name;
        self.mainwordView.name = [self.model.keyword stringByReplacingOccurrencesOfString:@"$" withString:@"  "];
        self.weiboWordView.name = self.model.weibokeyword;
        self.regionView.name = [KDReginDataTool getAreaNameWithID:[NSString stringWithFormat:@"%ld", (long)self.model.m_Region]];
        self.shareBtn.selected = self.model.m_Share;
        KDAccount *account = [KDAccountTool account];
        self.shareBtn.enabled = self.model.u_Id == account.userId;
        self.addKeywordView.enable = self.model.u_Id == account.userId;
        self.param.share = (self.model.m_Share) ? @"true":@"false";
        self.mismatchingWord.name = self.model.m_FileterKeyWord;
    }else{//否则就用默认值
        self.param.share = 0;
        KDBaesMonitorModel *model = [[KDBaesMonitorModel alloc]init];
        self.model = model;
    }
    
}
/**
 *  设置控制器底部scrollView
 */
- (void)setUpScrollView{
    //加一个挡板
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    //初始化underScrollView
    UIScrollView *underScrollView = [[UIScrollView alloc]init];
    self.underScrollView = underScrollView;
    underScrollView.frame = CGRectMake(0, 0, screenW, screenH);
    underScrollView.backgroundColor = BackGroundColor;
    underScrollView.showsHorizontalScrollIndicator = NO;
    underScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.underScrollView];

}
/**
 *  输入名称板块
 */
- (void)setUpAddKeyWordView{
    KDAddKeywordView *addKeywordView = [KDAddKeywordView addKeywordView];
    self.addKeywordView = addKeywordView;
    addKeywordView.delegate = self;
    addKeywordView.frame = CGRectMake(0, 10, screenW, AddKeyWordView_Height);
//    addKeywordView.chosen = YES;
    //    KDLog(@"%@",NSStringFromCGRect(self.addKeywordView.frame));
    [self.underScrollView addSubview:addKeywordView];
    
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(addKeywordView.frame), screenW, NOTICE_LINE_HEIGHT + 15);
    noticeView.title = @"请输入监测主题名称。(非本人添加不可修改！)";
    [self.underScrollView addSubview:noticeView];
    [self setUpShareBtn];
   
}
/**
 *  初始化共享按钮和加入专题监测按钮
 */
- (void)setUpShareBtn{
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareBtn = shareBtn;
    shareBtn.frame = CGRectMake(20, CGRectGetMaxY(self.addKeywordView.frame) + NOTICE_LINE_HEIGHT + 15, 120, 25);
    [shareBtn setTitle:@"单位共享" forState:UIControlStateNormal];
    shareBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [shareBtn setImage:[UIImage imageNamed:@"单位共享"] forState:UIControlStateNormal];
    [shareBtn setImage:[UIImage imageNamed:@"单位共享选中"] forState:UIControlStateSelected];
    shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    shareBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    [shareBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    shareBtn.backgroundColor = [UIColor clearColor];
    [shareBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.underScrollView addSubview:shareBtn];

}
/**
 *  设置地区板块
 */
- (void)setUpReginView{
    KDAddKeywordView *regionView = [KDAddKeywordView addKeywordView];
    regionView.frame = CGRectMake(0, CGRectGetMaxY(self.shareBtn.frame) + 10, screenW, AddKeyWordView_Height);
    regionView.delegate = self;
    regionView.type = 1;
    regionView.name = @"全国";
    self.regionView = regionView;
    [self.underScrollView addSubview:regionView];
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    self.noticeView1 = noticeView;
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(regionView.frame), screenW, NOTICE_LINE_HEIGHT + 15);
    noticeView.title = @"信息内容涉及的区域范围。";
    [self.underScrollView addSubview:noticeView];
}
/**
 *  设置关键词组板块
 */
- (void)setUpMainword{
    KDAddKeywordView *mainwordView = [KDAddKeywordView addKeywordView];
    mainwordView.frame = CGRectMake(0, CGRectGetMaxY(self.shareBtn.frame) + 10, screenW, AddKeyWordView_Height);
    mainwordView.delegate = self;
    mainwordView.type = 2;
    mainwordView.name = @"关键词组";
    self.mainwordView = mainwordView;
    [self.underScrollView addSubview:mainwordView];
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    self.noticeView2 = noticeView;
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(mainwordView.frame), screenW, NOTICE_LINE_HEIGHT *1.5 + 15);
    noticeView.title = @"温馨提示：同一组关键词的搜索机制是OR(或者)；不同组关键词的搜索机制是And(并且)。关键词组不超过5个。";
    [self.underScrollView addSubview:noticeView];
}
/**
 *  微博关键词组设置界面
 */
- (void)setUpsecondwordView{
    KDAddKeywordView *weiboWordView = [KDAddKeywordView addKeywordView];
    weiboWordView.frame = CGRectMake(0, CGRectGetMaxY(self.noticeView2.frame) + 10, screenW, AddKeyWordView_Height);
    weiboWordView.delegate = self;
    weiboWordView.type = 3;
    weiboWordView.name = @"微博关键词组";
    self.weiboWordView = weiboWordView;
    [self.underScrollView addSubview:weiboWordView];
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    self.noticeView3 = noticeView;
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(weiboWordView.frame), screenW, NOTICE_LINE_HEIGHT + 15);
    noticeView.title = @"温馨提示：微博订阅关键词需经由后台人工审核。";
    [self.underScrollView addSubview:noticeView];
}
/**
 *  不匹配关键词组设置界面
 */
- (void)setUpMismatchingWordView{
    KDAddKeywordView *mismatchingWord = [KDAddKeywordView addKeywordView];
    mismatchingWord.frame = CGRectMake(0, CGRectGetMaxY(self.noticeView3.frame) + 10, screenW, AddKeyWordView_Height);
    mismatchingWord.delegate = self;
    mismatchingWord.type = 4;
    mismatchingWord.name = @"不匹配词组";
    self.mismatchingWord = mismatchingWord;
    [self.underScrollView addSubview:mismatchingWord];
    //设置名称注释
    KDNoticeView *noticeView = [KDNoticeView noticeView];
    self.noticeView4 = noticeView;
    noticeView.frame = CGRectMake(0, CGRectGetMaxY(mismatchingWord.frame), screenW, NOTICE_LINE_HEIGHT + 15);
    noticeView.title = @"温馨提示：系统根据不匹配关键词对采集到的信息进行二次筛选。";
    [self.underScrollView addSubview:noticeView];
}
/**
 *  设置保存按钮
 */
- (void)setUpSaveBtn{
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(25, CGRectGetMaxY(self.noticeView4.frame)+ 15, screenW - 25*2, 30);
//    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setImage:[UIImage imageNamed:@"保存"] forState:UIControlStateNormal];
    [saveBtn setImage:[UIImage imageNamed:@"保存选中"] forState:UIControlStateHighlighted];
//    saveBtn.backgroundColor = [UIColor whiteColor];
//    [saveBtn setTitleColor:KDColor forState:UIControlStateNormal];;
    saveBtn.layer.cornerRadius = 7;
    saveBtn.clipsToBounds = YES;
    self.saveBtn = saveBtn;
    [self.underScrollView addSubview:saveBtn];
    self.underScrollView.contentSize = CGSizeMake(1, CGRectGetMaxY(self.saveBtn.frame)+64);
}
#pragma mark - 事件点击区
- (void)regionBtnClick:(UIButton *)regionBtn{
    KDProvinceController *vc = [[KDProvinceController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
/**
 *  共享按钮被点击了
 */
- (void)shareBtnClick:(UIButton *)shareBtn{
    
    shareBtn.selected = !shareBtn.selected;
    self.param.share = (shareBtn.selected) ? @"true":@"false";
}
/**
 *  加入专题按钮被点击了
 */
- (void)specialMonitorBtnClick:(UIButton *)specialMonitorBtn{
    specialMonitorBtn.selected = !specialMonitorBtn.selected;
}
/**
 *  保存按钮被点击了
 */
- (void)saveBtnClick:(UIButton *)saveBtn{
//    saveBtn.enabled = NO;
    if (self.add) {//表示是添加
         [self addRequest];
    }else{//标示是编辑
        [self editRequest];
    }
}
/**
 *  返回按钮被点击了
 */
- (void)backViewClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 网络请求去区
/**
 *  添加主题的请求
 */
- (void)addRequest{
    self.param.name = self.model.m_Name;
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *nameStr = [self.model.m_Name stringByTrimmingCharactersInSet:set];
    if (!self.model.m_Name.length || !self.model.m_Name ||!nameStr.length) {
        [SVProgressHUD showInfoWithStatus:@"监测主题名称不能为空！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    self.param.share = (self.shareBtn.selected) ?@"true": @"false";
    self.param.keyword = self.model.keyword;
     NSString *keywordStr = [self.model.keyword stringByTrimmingCharactersInSet:set];
    if (!self.model.keyword.length ||!keywordStr.length) {
        [SVProgressHUD showInfoWithStatus:@"关键词组不能为空！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    self.param.weiboKeyword = (!self.model.weibokeyword ) ? @"":self.model.weibokeyword;
    self.param.excludeKeyword = (!self.model.m_FileterKeyWord) ? @"":self.model.m_FileterKeyWord ;
    self.param.method = @"addMonitorKeywordSetting";
    [SVProgressHUD showWithStatus:@"正在保存" maskType:SVProgressHUDMaskTypeGradient ];
    [KDMonitorRequestTool addKeywordMonitorWithParam:self.param success:^(KDMKeywordAddResult *responseObejct)
    {
        if ([responseObejct.status isEqualToString:@"ok"])
        {//给个提示
            if (responseObejct.info  == -1 ) {//表示该主题已经存在了
                [SVProgressHUD showInfoWithStatus:@"该主题已存在！" maskType:SVProgressHUDMaskTypeGradient];
            }else if (responseObejct.info  == 1 ){
                [SVProgressHUD showSuccessWithStatus:@"主题添加成功！" maskType:SVProgressHUDMaskTypeGradient];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                 [SVProgressHUD showInfoWithStatus:@"主题添加失败！" maskType:SVProgressHUDMaskTypeGradient];
            }
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"未知错误！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@", error);
    }];
}
/**
 *  编辑保存的请求
 */
- (void)editRequest{
    self.param.name = self.model.m_Name;
    if (!self.model.m_Name.length) {
        [SVProgressHUD showInfoWithStatus:@"主题名称不能为空！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    self.param.share = (self.shareBtn.selected) ?@"true": @"false";
    self.param.keyword = self.model.keyword;
    if (!self.model.keyword.length) {
        [SVProgressHUD showInfoWithStatus:@"关键词组不能为空！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    self.param.weiboKeyword = self.weiboWordView.name;
    self.param.excludeKeyword = self.mismatchingWord.name;
    self.param.method = @"editMonitorKeywordSetting";
    self.param.m_Id = [self.model.m_Id integerValue];
    self.param.name_status = ([self.param.name isEqualToString:self.originalName]) ? @"false":@"true";
//    self.param.M_Region = self.model.m_Region;
    [KDMonitorRequestTool addKeywordMonitorWithParam:self.param success:^(KDMKeywordAddResult *responseObejct)
     {
         if ([responseObejct.status isEqualToString:@"ok"])
         {//给个提示
             if (responseObejct.info  == -1 ) {//表示该主题已经存在了
                 [SVProgressHUD showInfoWithStatus:@"该主题已存在！" maskType:SVProgressHUDMaskTypeGradient];
             }else if (responseObejct.info  == 1 ){
                 [SVProgressHUD showInfoWithStatus:@"主题编辑成功！" maskType:SVProgressHUDMaskTypeGradient];
             }else{
                 [SVProgressHUD showInfoWithStatus:@"主题编辑失败！" maskType:SVProgressHUDMaskTypeGradient];
             }
             [self.navigationController popViewControllerAnimated:YES];

         }
     } failure:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"未知错误！" maskType:SVProgressHUDMaskTypeGradient];
         
         KDLog(@"%@", error);
     }];
}
#pragma mark - 通知
/**
 *  接收到返回的地址信息
 */
- (void)getAddress:(NSNotification *)noty{
    NSString *text = noty.userInfo[@"address"];
//    self.param.M_Region = [noty.userInfo[@"ID"] integerValue];
    if (self.model) {//如果是从编辑进来的，就让region的赋值由model负责
        KDReginType *model = noty.userInfo[@"regionModel"];
        self.model.m_Region =model.ID;
    }
    self.regionView.name = text;
    self.regionView.chosen = YES;
}
#pragma mark - KDAddKeywordViewDelegate
/**
 *  主题名称按钮被点击了
 */
- (void)KDAddKeywordView:(KDAddKeywordView *)nameView DidSelectWithType:(NSInteger)type{
    self.hidesBottomBarWhenPushed = YES;
    switch (type) {
        case 0://跳转进入名称修改
        {
            KDKeywordNameController *namevc = [[KDKeywordNameController alloc]init];
            namevc.delegate = self;
//            if (!self.add) {
                namevc.name = _model.m_Name;
//            }
            [self.navigationController pushViewController:namevc animated:YES];
            
            break;
    }
        case 1://跳转进入地区选择
        {
            KDProvinceController *vc = [[KDProvinceController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 2://跳转进入关键词组编辑
        {
            KDKeywordGroupEditController *vc = [[KDKeywordGroupEditController alloc]init];
            vc.delegate = self;
            vc.type = 0;
            vc.keywordGroupstr =  self.model.keyword;
            
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 3://跳转进入微博关键词编辑
        {
            KDKeyWordEditController *vc = [[KDKeyWordEditController alloc]init];
            vc.delegate = self;
            vc.type = 1;
            vc.infoArr =  [self getKeywordArrFromKeyword:self.model.weibokeyword];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 4://跳转进入不匹配词编辑
        {
            KDKeyWordEditController *vc = [[KDKeyWordEditController alloc]init];
            vc.delegate = self;
            vc.type = 2;//
            vc.infoArr =  [self getKeywordArrFromKeyword:self.model.m_FileterKeyWord];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
            
        default:
            break;
    }
}
/**
 *  将keyword一长串不分割的字符串分割成单个用数组装起来
 */
- (NSArray *)getKeywordArrFromKeyword:(NSString *)keyword{
    if (keyword.length == 0) {//如果没有，就让她没有
        return nil;
    }
    NSMutableArray *tempArr = [NSMutableArray array];
    NSArray *arr = [keyword componentsSeparatedByString:@","];
    for (int i = 0 ; i < arr.count; i++) {
        KDEditeCellModel *model = [[KDEditeCellModel alloc]init];
        model.name = arr[i];
//        model.num = i;
        [tempArr addObject:model];
    }
    return tempArr;
}
#pragma mark - KDKeywordNameControllerDelegate
/**
 *  当结束编辑时会调用这个方法
 */
- (void)nameController:(KDKeywordNameController *)nameCtr finishedEditWith:(NSString *)name{
    self.addKeywordView.name = (name.length)?name:@"监测名称";
    self.model.m_Name = name;
    self.addKeywordView.chosen = YES;
}

#pragma mark - KDKeyWordEditControllerDelegate
/**
 *  从编辑界面返回来会调用这个方法
 */
- (void)editController:(KDKeyWordEditController *)editCtr finishedEditWith:(NSString *)name{
    if (editCtr.type - 1) {//不匹配词关键词返回来的
        self.mismatchingWord.name = (name.length)?name:@"不匹配词组";
        self.model.m_FileterKeyWord = name;
    }else{//微博次组返回来的
         self.weiboWordView.name = (name.length)?name:@"微博关键词组";
        self.model.weibokeyword = name;
    }
}
#pragma mark - KDKeywordGroupEditControllerDelegate
/**
 *  获取从关键词组返回的名字
 */
- (void)groupEditController:(KDKeywordGroupEditController *)editCtr finishedEditWith:(NSString *)name{
    self.model.keyword = name;
    NSString *nameStr = [name stringByReplacingOccurrencesOfString:@"$" withString:@"  "];
    self.mainwordView.name = (name.length)?nameStr:@"关键词组";
}

#pragma mark -UIAlertViewDelegate

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
